<?php
namespace Admin\Model;
use Think\Model;

class AdminModel extends Model {
	protected $_validate = array(
		array('username', 'require', '用户名不能为空', 0, 'regex', 1),
		array('username', 'checkUserName', '用户不存在', 0, 'callback', 1),
		array('password', 'require', '密码不能为空', 0, 'regex', 1),
		array('password', 'checkPwd', '密码错误', 0, 'callback', 1),
		/** 增加后台用户验证 **/
		array('username', 'require', '用户名不能为空', 0, 'regex', 4),
		array('password', 'require', '密码不能为空', 0, 'regex',4),
		array('roleid', 'require', '请选择角色', 0, 'regex', 4),

	);

	protected $_auto = array(
		array('password', 'md5', 1, 'function'),
		array('lastlogintime', 'time', 1, 'function'),
		array('lastloginip', 'get_client_ip', 1, 'function'),
	);

	/**
	 * 检查用户名
	 * @return [type] [description]
	 */
	public function checkUserName() {
		$username = I('post.username');

		$res = $this->where(array('username' => $username))->getField('id');
		if($res) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检查用户密码
	 * @return [type] [description]
	 */
	public function checkPwd() {
		$username = I('post.username');
		$password = I('post.password');

		$map['username'] = $username;
		$map['password'] = md5($password);
		$res = $this->where($map)->find();
		if($res) {
			$this->lastloginip = get_client_ip();
			$this->lastlogintime = time();
			$this->where(array('id' => $res['id']))->save();
			$this->setLogin($res);
			return true;
		} else {
			return false;
		}		
	}

	/**
	 * 设置登录信息
	 * @param [type] $res [description]
	 */
	public function setLogin($array) {
        session('admin_uid', $array['id']);
        session('admin_username', $array['username']);
        // session('auth_id', $array['authid']);		
	}

}